//
//  ZJReportViewController.m
//  ShangHaiHuDongApp
//
//  Created by ZJ on 2017/6/14.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "ZJReportViewController.h"
#import "ZJOrganizationSelectView.h"
#import "ZJReportDetailViewController.h"
#import "OrganizationViewSelectController.h"
#import "ZJBOorganizationModel.h"
#define CellID @"OrganizationViewSelectController"
@interface ZJReportViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger _index;/**< 标记点击的是那个输入框  0：街道  1：居民区 */
    NSIndexPath *_indexPath;/**< 来记录选择框的选择 */
}
/** 街道选择框 */
@property (nonatomic, strong) ZJOrganizationSelectView *streetSelectView;
/** 报到处选择框 */
@property (nonatomic, strong) ZJOrganizationSelectView *reportSelectView;
/** 报到时间 */
@property (nonatomic, strong) ZJOrganizationSelectView *timeView;
/** 所在地 */
@property (nonatomic, strong) UILabel *site;
/** 下一步 */
@property (nonatomic, strong) UIButton *nextButton;

/** tableView */
@property (nonatomic, strong) UITableView *tableView;
/** 街道数据 */
@property (nonatomic, strong) NSMutableArray *streetDataArray;
/** 党组织数据 */
@property (nonatomic, strong) NSMutableArray *organizationDataArray;
@end

@implementation ZJReportViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titlelabel.text = @"党员报到";
    _indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self netWorking_street];
    [self setupUI];
    [self isCheck];
}
- (void)action_leftButton:(UIButton *)sender{
    if (self.isModel) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)setupUI{
//    //到居住地党组织报到 :
//    UILabel *label = [self newLabe_text:@"到居住地党组织报到"];
//    //所在区的下划线
//    UILabel *labelLine = [UILabel new];
//    labelLine.backgroundColor = [UIColor zj_colorWithHexString:@"ebebeb"];
//    //所在地
//    UILabel *siteHitt = [self newLabe_text:@"所在区 :"];
//    //所在区的下划线
//    UILabel *underLine = [UILabel new];
//    underLine.backgroundColor = [UIColor zj_colorWithHexString:@"ebebeb"];
    //街道
    UILabel *streetHitt = [self newLabe_text:@"街道 :"];
    //街道
    UILabel *reportHitt = [self newLabe_text:@"居住地党组织 :"];
//    [self.view addSubview:label];
//    [self.view addSubview:labelLine];
//    [self.view addSubview:siteHitt];
    [self.view addSubview:streetHitt];
    [self.view addSubview:reportHitt];
//    [self.view addSubview:underLine];
//    [self.view addSubview:self.site];
    [self.view addSubview:self.reportSelectView];
    [self.view addSubview:self.streetSelectView];
//    [self.view addSubview:self.nextButton];
//    label.sd_layout
//    .topSpaceToView(self.view, navHeight)
//    .leftSpaceToView(self.view, 25 * [UIScreen zj_screenWScale])
//    .heightIs(43 * [UIScreen zj_screenHScale])
//    .widthIs([NSString zj_sizeOfString:label.text font:siteHitt.font width:self.view.width].width);
//    
//    labelLine.sd_layout
//    .topSpaceToView(label, 0)
//    .leftSpaceToView(self.view, 0)
//    .widthIs(self.view.width)
//    .heightIs(1);
//    
//    siteHitt.sd_layout
//    .topSpaceToView(labelLine , 0)
//    .leftSpaceToView(self.view, 25 * [UIScreen zj_screenWScale])
//    .heightIs(43 * [UIScreen zj_screenHScale])
//    .widthIs([NSString zj_sizeOfString:siteHitt.text font:siteHitt.font width:self.view.width].width);
//    
//    self.site.sd_layout
//    .topEqualToView(siteHitt)
//    .leftSpaceToView(siteHitt, 10 * [UIScreen zj_screenWScale])
//    .rightSpaceToView(self.view, 25 * [UIScreen zj_screenWScale])
//    .heightRatioToView(siteHitt, 1);
//    
//    underLine.sd_layout
//    .topSpaceToView(self.site, 0)
//    .leftSpaceToView(self.view, 0)
//    .widthIs(self.view.width)
//    .heightIs(1);
//    
    streetHitt.sd_layout
    .topSpaceToView(self.view, navHeight  + 30 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 25 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 25 * [UIScreen zj_screenWScale])
    .heightIs([NSString heightWithTextFont:streetHitt.font]);
    
    self.streetSelectView.sd_layout
    .topSpaceToView(streetHitt, 11 * [UIScreen zj_screenHScale])
    .leftEqualToView(streetHitt)
    .rightEqualToView(streetHitt)
    .heightIs(44 * [UIScreen zj_screenHScale]);

    reportHitt.sd_layout
    .topSpaceToView(self.streetSelectView, 18 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 25 * [UIScreen zj_screenWScale])
    .rightEqualToView(streetHitt)
    .heightRatioToView(streetHitt, 1);
    
    self.reportSelectView.sd_layout
    .topSpaceToView(reportHitt, 11 * [UIScreen zj_screenHScale])
    .leftEqualToView(streetHitt)
    .rightEqualToView(streetHitt)
    .heightRatioToView(self.streetSelectView, 1);
    
    self.nextButton.sd_layout
    .bottomSpaceToView(self.view, 30 * [UIScreen zj_screenHScale])
    .leftSpaceToView(self.view, 28 * [UIScreen zj_screenWScale])
    .rightSpaceToView(self.view, 28 * [UIScreen zj_screenWScale])
    .heightIs(44 * [UIScreen zj_screenHScale]);
    
    [self.view addSubview:self.tableView];
    self.tableView.hidden = YES;
    self.tableView.sd_layout
    .widthRatioToView(self.streetSelectView, 1)
    .heightIs(200 * [UIScreen zj_screenHScale]);
}

- (UILabel *)newLabe_text:(NSString *)text{
    UILabel *label = [UILabel new];
    label.textColor = [UIColor textBlackColor];
    label.font = [UIFont titleTextFont];
    label.text = text;
    return label;
}

#pragma mark - 判断是否党员报到审核中
- (void)isCheck{
    if ([[ZJUserInfoModel sharedUserInfo].USER_MODEL_JOB.AUTH_STATUS isEqualToString:@"1"]) {//审核中
        self.streetSelectView.userInteractionEnabled = NO;
        self.reportSelectView.userInteractionEnabled = NO;
        self.streetSelectView.backgroundColor = [UIColor themeGrayColor];
        self.reportSelectView.backgroundColor = [UIColor themeGrayColor];
        self.nextButton.userInteractionEnabled = NO;
        [self.nextButton setTitle:@"正在审核中" forState:UIControlStateNormal];
        self.nextButton.backgroundColor = [UIColor zj_colorWithHexString:@"bdbdbd"];
        [self.nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
//        else if( [[ZJUserInfoModel sharedUserInfo].USER_MODEL_JOB.AUTH_STATUS isEqualToString:@"2"]) {//认证通过重新审核
//        [self.nextButton setTitle:@"重新报到" forState:UIControlStateNormal];
//    }
}
#pragma mark - 网络请求
//请求街道
- (void)netWorking_street{
    __weak typeof(self) weakSelf = self;
    [[LPShowNoDataManager showNoDataManager] removeEmptyView];
    [YJProgressHUD showMessage:@"加载中..." duration:10 view:self.view];
    NSDictionary *dict = @{@"STREET_ID":@""};
    [NetWorkingManager postWithUrlString:[NetWorkingURL listDeptByCategory] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        [YJProgressHUD hide];
        if ([model.STATE isEqualToString:@"20000"]) {
            weakSelf.streetDataArray = [[NSArray yy_modelArrayWithClass:[ZJBOorganizationModel class] json:[object objectForKey:@"ORG_STREETS"]] mutableCopy];
            weakSelf.organizationDataArray =[[NSArray yy_modelArrayWithClass:[ZJBOorganizationModel class] json:[object objectForKey:@"ORG_RESIDENTIALS"]] mutableCopy];
            
            [weakSelf userInfo_initUI];
           
        }else{
            [[LPShowNoDataManager showNoDataManager] showEmptyViewWithErrorView:weakSelf.view];
            [LPShowNoDataManager showNoDataManager].noContentViewTapedBlock = ^{
                [weakSelf netWorking_street];
            };

        }
    } Fail:^(id object) {
        [YJProgressHUD hide];
        [[LPShowNoDataManager showNoDataManager] showEmptyViewWithErrorView:weakSelf.view];
        [LPShowNoDataManager showNoDataManager].noContentViewTapedBlock = ^{
            [weakSelf netWorking_street];
        };
    }];
}

//请求党组织
- (void)netWorking_organization{
    __weak typeof(self) weakSelf = self;
    [YJProgressHUD showMessage:@"加载中..." duration:10 view:self.view];
    ZJBOorganizationModel *model = self.streetDataArray[_indexPath.section];
    NSDictionary *dict = @{@"STREET_ID":model.ID};
    [NetWorkingManager postWithUrlString:[NetWorkingURL getCheckInResidentials] Parameter:dict Success:^(id object) {
        NetWorkModel *model = [NetWorkModel yy_modelWithJSON:object];
        [YJProgressHUD hide];
        if ([model.STATE isEqualToString:@"20000"]) {
            weakSelf.organizationDataArray = [[NSArray yy_modelArrayWithClass:[ZJBOorganizationModel class] json:[object objectForKey:@"ORG_RESIDENTIALS"]] mutableCopy];
            
        }else{
            [YJProgressHUD showMessage:@"加载失败" inView:weakSelf.view];
            [weakSelf.organizationDataArray removeAllObjects];
        }
        [weakSelf local_organization];
    } Fail:^(id object) {
        [YJProgressHUD showMessage:@"加载失败" inView:weakSelf.view];
        [weakSelf.organizationDataArray removeAllObjects];
        [weakSelf local_organization];
    }];
}

//根据本地数据来初始化界面
- (void)userInfo_initUI{
    if (![ZJUserInfoModel sharedUserInfo].DEPT_MODEL_JOB) {//注册页面
        [self initViewUI];//_indexPath:{0,0}
        self.nextButton.hidden = NO;
        return;
    }
    //不是注册页面
    ZJDeptModel *mode = [ZJUserInfoModel sharedUserInfo].DEPT_MODEL_JOB;
    [self.streetDataArray enumerateObjectsUsingBlock:^(ZJBOorganizationModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([mode.GLOBALID rangeOfString:obj.GLOBALID].location != NSNotFound) {//包含
            _indexPath = [NSIndexPath indexPathForRow:_indexPath.row inSection:idx];
        }
    }];
    //第一个不需要网络请求
    if (_indexPath.section == 0) {
        [self local_organization];
    }else{//需要网络请求
        [self netWorking_organization];
    }
    self.nextButton.hidden = NO;
}
//查询本地的党组织
- (void)local_organization{
    ZJDeptModel *mode = [ZJUserInfoModel sharedUserInfo].DEPT_MODEL_JOB;
    [self.organizationDataArray enumerateObjectsUsingBlock:^(ZJBOorganizationModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.ID isEqualToString:mode.ID]) {
            _indexPath = [NSIndexPath indexPathForRow:idx inSection:_indexPath.section];
        }
    }];
    [self initViewUI];
}

//初始化赋值
- (void)initViewUI{
    if (self.streetDataArray.count > 0) {
        ZJBOorganizationModel *model = self.streetDataArray[_indexPath.section];
        self.streetSelectView.textField.text = model.DEPTABBREVIATION;
        if (self.organizationDataArray.count > 0) {
            ZJBOorganizationModel *model1 = self.organizationDataArray[_indexPath.row];
            self.reportSelectView.textField.text = model1.DEPTABBREVIATION;
        }else{
            self.reportSelectView.textField.text = @"无";
        }
    }
}
#pragma mark - 点击事件
//下一步
- (void)action_nextButtinClick{
    
    if (self.organizationDataArray.count <= _indexPath.row) {
        [YJProgressHUD showMsgWithoutView:@"居住地党组织不存在，不能进行下一步"];
        return;
    }
    if ([self.nextButton.titleLabel.text isEqualToString:@"重新报到"]) {//重新报到
       ZJBOorganizationModel *model =  self.organizationDataArray[_indexPath.row];
        if ([model.ID isEqualToString:[ZJUserInfoModel sharedUserInfo].DEPT_MODEL_JOB.ID]) {//未改变
            [YJProgressHUD showMessage:@"未更换居民区" inView:self.view afterDelayTime:2];
        }else{//改变居民区
            [self alertCorntoller];
        }
        return;
    }
    ZJReportDetailViewController *vc = [ZJReportDetailViewController new];
    vc.model = self.organizationDataArray[_indexPath.row];
    vc.registerModel = self.registerModel;
    vc.isModel = self.isModel;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)alertCorntoller{
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您已更换了居住地, 可通过次功能进行党员再报到, 请确认是否继续 ?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"继续" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ZJReportDetailViewController *vc = [ZJReportDetailViewController new];
        vc.model = self.organizationDataArray[_indexPath.row];
        vc.registerModel = self.registerModel;
        vc.isModel = self.isModel;
        [self.navigationController pushViewController:vc animated:YES];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)action_TapGester:(UITapGestureRecognizer *)gesture{
    if (self.tableView.isHidden == NO) {//当天表显示
        self.tableView.hidden = YES;
        return;
    }
    if (gesture.view == self.streetSelectView) {//街道选择框
        _index = 0;
        
    }else if (gesture.view == self.reportSelectView){//居民区输入框
        _index = 1;
    }
    self.tableView.origin = CGPointMake(gesture.view.x , gesture.view.bottom + 5 *[UIScreen zj_screenHScale]);
    
    [self.tableView reloadData];
    self.tableView.hidden = NO;
}

#pragma mark - UITableView 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_index == 0) {
      return self.streetDataArray.count;
    }
    if (self.organizationDataArray.count < 1) {
        tableView.hidden = YES;
    }
    return self.organizationDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID forIndexPath:indexPath];
    cell.textLabel.font = [UIFont titleTextFont];
    cell.textLabel.textColor = [UIColor textBlackColor];
    if (_index == 0) {
        ZJBOorganizationModel *model = self.streetDataArray[indexPath.row];
        cell.textLabel.text = model.DEPTABBREVIATION;
    }else{
        ZJBOorganizationModel *model1 = self.organizationDataArray[indexPath.row];
        cell.textLabel.text = model1.DEPTABBREVIATION;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_index == 0) {
        if (_indexPath.section == indexPath.row) {
            self.tableView.hidden = YES;
            return;
        }
        _indexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        ZJBOorganizationModel *model = self.streetDataArray[_indexPath.section];
        self.streetSelectView.textField.text = model.DEPTABBREVIATION;
        [self netWorking_organization];
    }else{
        _indexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:_indexPath.section];
        ZJBOorganizationModel *model1 = self.organizationDataArray[_indexPath.row];
        self.reportSelectView.textField.text = model1.DEPTABBREVIATION;
    }
    self.tableView.hidden = YES;
}





#pragma mark - Setter
#pragma mark - Getters

- (UILabel *)site{
    if (_site == nil){
        _site = [UILabel new];
        _site.textColor = [UIColor textBlackColor];
        _site.font = [UIFont titleTextFont];
        _site.text = @"市北党建云";
    }
    return _site;
}

- (ZJOrganizationSelectView *)streetSelectView{
    if (_streetSelectView == nil){
        _streetSelectView = [[ZJOrganizationSelectView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        UITapGestureRecognizer *tapGester = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(action_TapGester:)];
        [_streetSelectView addGestureRecognizer:tapGester];
        _streetSelectView.textField.userInteractionEnabled = NO;
    }
    return _streetSelectView;
}
- (ZJOrganizationSelectView *)reportSelectView{
    if (_reportSelectView == nil){
        _reportSelectView = [[ZJOrganizationSelectView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
      
        UITapGestureRecognizer *tapGester = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(action_TapGester:)];
        [_reportSelectView addGestureRecognizer:tapGester];
        _reportSelectView.textField.userInteractionEnabled = NO;
    }
    return _reportSelectView;
}
- (ZJOrganizationSelectView *)timeView{
    if (_timeView == nil){
        _timeView = [[ZJOrganizationSelectView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _timeView.textField.userInteractionEnabled = NO;
    }
    return _timeView;
}
- (UIButton *)nextButton{
    if (_nextButton == nil){
        _nextButton = [[UIButton alloc] init];
        [_nextButton setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _nextButton.titleLabel.font = [UIFont titleTextFont];
        _nextButton.backgroundColor = [UIColor themeColor];
        _nextButton.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        [_nextButton addTarget:self action:@selector(action_nextButtinClick) forControlEvents:UIControlEventTouchUpInside];
        _nextButton.hidden = YES;
    }
    return _nextButton;
}
- (UITableView *)tableView{
    if (_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, navHeight, self.view.width, self.view.height  - navHeight ) style:UITableViewStylePlain];
        //        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.layer.borderColor = [UIColor zj_colorWithHexString:@"ededed"].CGColor;
        _tableView.layer.borderWidth = 1;
        _tableView.layer.cornerRadius = 4 * [UIScreen zj_screenWScale];
        _tableView.tableFooterView = [UIView new];
        [_tableView  registerClass:[UITableViewCell class] forCellReuseIdentifier: CellID];
        
    }
    return _tableView;
}

- (NSMutableArray *)streetDataArray{
    if (_streetDataArray == nil){
        _streetDataArray = [NSMutableArray array];
        
    }
    return _streetDataArray;
}

- (NSMutableArray *)organizationDataArray{
    if (_organizationDataArray == nil){
        _organizationDataArray = [NSMutableArray array];
        
    }
    return _organizationDataArray;
}
@end



